package com.ddxz.tool.sql.dynamic;

import com.ddxz.tool.core.convert.DateUtil;
import com.ddxz.tool.sql.struct.DataSourceInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @description
 * @author 朱宗刚
 * @date 2019年12月19日
 * @version 1.0.0
 */

@Slf4j
public class DdxzDataSourceContextHandler {
    private static final int INVALID_DAYS = 30;

    private static final ThreadLocal<DataSourceInfo> CONTEXT_HOLDER = ThreadLocal.withInitial(() -> {
        DataSourceInfo dsi = new DataSourceInfo();
        dsi.setKey("major");
        return dsi;
    });

    public static Map<Object, Long> dataSourceKeys = new HashMap<>();

    public static void setDataSource(DataSourceInfo dsi) {
        log.debug("new database connections: {}", dsi);
        CONTEXT_HOLDER.set(dsi);
    }

    public static DataSourceInfo getDataSource() {
        log.debug("current DatasourceInfo: {}", CONTEXT_HOLDER.get());
        return CONTEXT_HOLDER.get();
    }

    public static void clearDataSource() {
        CONTEXT_HOLDER.remove();
    }

    public static boolean containDataSourceKey(DataSourceInfo key) {
        if(dataSourceKeys.containsKey(key)) {
            long interval = DateUtil.getTimestamp() - dataSourceKeys.get(key);
            if(interval > DateUtil.MILLISECOND_PER_DAY * INVALID_DAYS) {
                dataSourceKeys.remove(key);
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    public static boolean addDataSourceKey(Collection<? extends Object> keys) {
        try {
            keys.forEach(item -> dataSourceKeys.put(item, DateUtil.getTimestamp()));
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
